package com.horizon.api;

import com.horizon.common.Const;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.SimpleIdGenerator;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserApi {
    /**
     * 登录
     */
    @PostMapping("/login")
    public ResponseEntity<Boolean> login(@RequestBody Map<String, String> user, HttpServletResponse response) {
        HttpStatus status = HttpStatus.UNAUTHORIZED;

        if ("admin".equals(user.get("username")) && "21232f297a57a5a743894a0e4a801fc3".equals(user.get("password"))) {
            response.setHeader(Const.ACCESS_TOKEN, "21232f297a57a5a743894a0e4a801fc3");
            response.setHeader(Const.ACCESS_TOKEN_ALIVE, (2 * 60 * 60 * 1000) + "");
            status = HttpStatus.OK;
        }

        return new ResponseEntity(true, status);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public ResponseEntity logout(@RequestHeader HttpHeaders headers) {
        List<String> access_token = headers.get(Const.ACCESS_TOKEN);
        if (access_token != null && access_token.size() > 0) {
            System.out.println("清空Token===" + access_token.get(0));
        }

        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, String>> info(@RequestHeader HttpHeaders headers) {
        List<String> access_token = headers.get(Const.ACCESS_TOKEN);
        if (access_token != null && access_token.size() > 0) {
            System.out.println("解析Token===" + access_token.get(0));
        }

        Map<String, String> user = new HashMap<>();
        user.put("fdId", String.valueOf(new SimpleIdGenerator().generateId()));
        user.put("username", "admin");
        user.put("nickname", "王富委");
        user.put("avatar", "https://hichatx.hisense.com/space/c/photo/load?id=5bd8f2bb84aefae78235dce0");
        user.put("dept", "财务共享中心");

        System.out.println(user);

        return new ResponseEntity<>(user, HttpStatus.OK);
    }
}
